package com.fly.common.mapper;

import org.apache.ibatis.mapping.MappedStatement;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.SqlHelper;
import tk.mybatis.mapper.provider.base.BaseSelectProvider;

import java.util.Iterator;
import java.util.Set;

/**
 * @CLASSNAME: MySelectProvider
 * @author: Fly
 * 日期: 2020/6/27  17:55
 * 描述:
 **/
public class MySelectProviderPage extends BaseSelectProvider {


    /* * 
     *@author Fuly
     * 
     * 日期：2020/6/27 17:56
     * 
     * 描述：
     *
     */
    public MySelectProviderPage(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }
    public MySelectProviderPage(){
        super(null,null);
    }

    /* * 
     *@author Fuly
     * 
     * 日期：2020/6/27 18:10
     * 
     * 描述：自定义sql
     *
     */
    public String selectList(MappedStatement ms) {
        StringBuilder sql = new StringBuilder();
        final Class<?> entityClass = getEntityClass(ms);
        // 修改返回值类型为实体类型
        setResultType(ms, entityClass);
        sql.append(SqlHelper.selectAllColumns(entityClass));
        sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));
        //sql.append(SqlHelper.whereAllIfColumns(entityClass, isNotEmpty()));
        sql.append(whereLikePageAllColumn(entityClass));
        sql.append(SqlHelper.orderByDefault(entityClass));
        return sql.toString();
    }



    /**
     *@author Fuly
     *
     * 日期：2020/7/4 23:23
     *
     * 描述：自定义模糊查询所有列sql用于查询显示
     */
    private String whereLikePageAllColumn(Class<?> entityClass) {
        StringBuilder sql = new StringBuilder();
        sql.append("<where>");
        Set<EntityColumn> columnSet = EntityHelper.getColumns(entityClass);
        Iterator var5 = columnSet.iterator();
        columnSet.forEach(col->{
            sql.append("<if test=\"");
            sql.append(col.getProperty());
            sql.append(" != null and ");
            sql.append(col.getProperty());
            sql.append(" != ''\">");
            sql.append(" AND ");
            sql.append(col.getColumn());
            //防止不同类型数据库函数不支持问题
            sql.append(" LIKE CONCAT('%',CONCAT(");
            sql.append(col.getColumnHolder());
            sql.append(",'%'))");
            sql.append("</if>");
        });
        sql.append("</where>");
        return sql.toString();
    }
}
